#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Version: Python 2.6.6
# Author: Sergey K.
# Created: 2011-11-01


import unittest

import rs

from rs.error import ErrorManager, build_error_handler


class ErrorManagerTest(unittest.TestCase):


    def setUp(self):
        @rs.error(404)
        @rs.produces('application/json')
        def not_found(response=rs.context.response):
            pass

        @rs.error(400)
        def bad_request(response=rs.context.response):
            pass
        self.not_found, self.bad_request = not_found, bad_request

    def tearDown(self):
        ErrorManager.error_handlers.clear()

    def test_init(self):
        eq = self.assertEquals
        true = self.assertTrue
        e = ErrorManager()
        eq(2, len(e.handlers))
        true(404 in e.handlers)
        true(400 in e.handlers)
        eq(self.not_found, e.handlers[404].target)
        eq(self.bad_request, e.handlers[400].target)

    def test_get_error_handler(self):
        eq = self.assertEquals
        true = self.assertTrue
        e = ErrorManager()
        true(e.has_error_handler(404))
        true(e.has_error_handler(400))
        true(not e.has_error_handler(500))
        h = e.get_error_handler(404)
        eq(self.not_found, h.target)
        h = e.get_error_handler(400)
        eq(self.bad_request, h.target)

    def test_build_error_handler(self):
        e, h = build_error_handler(self.not_found)
        eq = self.assertEquals
        true = self.assertTrue
        eq(404, e)
        true(h.target is self.not_found)
        true(h.producer is not None)
        eq('application/json', h.producer[0])
        e, h = build_error_handler(self.bad_request)
        eq(400, e)
        true(h.target is self.bad_request)
        true(h.producer is None)


if __name__ == '__main__':
    unittest.main()